package com.bootdo.wechat.config;

import com.bootdo.wechat.domain.MpConfigDO;
import com.bootdo.wechat.service.MpConfigService;
import com.bootdo.wechat.service.impl.MpConfigServiceImpl;
import me.chanjar.weixin.mp.api.WxMpInMemoryConfigStorage;
import me.chanjar.weixin.mp.api.WxMpMessageRouter;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.api.impl.WxMpServiceImpl;

import java.util.ArrayList;
import java.util.List;

public class WxHandlerInitialize  {


    private List<WxMpInMemoryConfigStorage> getConfigInDatabase(){
        //TODO: 从数据库中读取所有公众号信息，再构造WxMpInMemoryConfigStorage对象。
        List<WxMpInMemoryConfigStorage> listWx = new ArrayList<>();
        MpConfigService mpConfigService = new MpConfigServiceImpl();
        List<MpConfigDO> list = mpConfigService.selectMpList();
        if (list==null){
            return listWx;
        }
        for (MpConfigDO wpp: list
             ) {
            WxMpInMemoryConfigStorage wm = new WxMpInMemoryConfigStorage();
            wm.setAppId(wpp.getMpAppId());
            wm.setSecret(wpp.getMpAppSecret());
            wm.setToken(wpp.getMpToken());
            wm.setAesKey(wpp.getMpAesKey());
            listWx.add(wm);
        }
        return listWx;
    }

    public  void init(){
        System.out.println("初始化啦~~~~~");
        List<WxMpInMemoryConfigStorage> list =  getConfigInDatabase();
        for (WxMpInMemoryConfigStorage config: list) {
            WxMpService wxMpService = new WxMpServiceImpl();
            wxMpService.setWxMpConfigStorage(config);
            router(wxMpService);
        }
    }

    public WxMpMessageRouter router(WxMpService wxMpService) {
        WxMpMessageRouter getrouter = new Router().getrouter(wxMpService);
        return getrouter;
    }
}
